var mongoose = require('mongoose');
const newComment = require('../models/newscomment.model');
//新建评论
exports.create = function(req, res, next) {
    const com = new newComment(req.body);
    com.save().then((data) => {
        res.json(data);
    });
}

exports.update = function(req, res, next) {
    const id = req.params.id;
    // res.send(id);
    newComment.findByIdAndUpdate(id, { $set: req.body }, { new: false })
        .then(data => {
            res.json(data); // 这里返回的数据是修改之前的数据，不是修改之后的数据
        })
}

// 移除相应的id的数据
exports.remove = function(req, res, next) {
    const id = req.params.id;
    newComment.findByIdAndDelete(id, (err, data) => {
        res.json(data);
    })
}

//
exports.list = function(req, res, next) {
    var page = req.body.page ? req.body.page : 1;
    var limit = req.body.limit ? req.body.limit : 5;

    var queryCondition = {}; //查询条件
    if (req.body.title && req.body.title.trim().length > 0) {
        title = req.body.title;
        queryCondition = {
            "title": new RegExp(title, 'i')
        }
    }
    //分类Id
    if (req.body.cateId && req.body.cateId.trim().length > 0) {
        cateId = req.body.cateId;
        queryCondition = Object.assign(queryCondition, {
            cateId: cateId
        })
    }
    //用户Id
    if (req.body.userId && req.body.userId.trim().length > 0) {
        userId = req.body.userId;
        queryCondition = Object.assign(queryCondition, {
            userId: userId
        })
    }
    //新闻Id
    if (req.body.newsId && req.body.newsId.trim().length > 0) {
        newsId = req.body.newsId;
        queryCondition = Object.assign(queryCondition, {
            newsId: newsId
        })
    }
    console.log(queryCondition)

    newComment.paginate(queryCondition, { page: +page, limit: +limit }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    });

}

// 查询相应id信息
exports.getData = function(req, res, next) {
    var id = req.params.id;
    newComment.findById(id).then(data => {
        res.json(data);
    })

}

exports.removes = function(req, res, next) {
    var ids = req.body.ids.split(',')
    console.log(ids);
    if (ids.length > 0) {
        newComment.remove({ _id: { $in: ids } }).then(data => {
            res.json({ 'message': 'delete ok', status: 200 })
        })
    }
}